package net.tp.io;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

public class BitInputStream implements Closeable {

	private static final int EOF = -1;
	
	private final InputStream inputStream;
	private int buffer;
	private int n;
	
	public BitInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	@Override
	public void close() throws IOException {
		if (inputStream != null) {
			inputStream.close();
		}
	}
	
	public boolean eof() {
		return buffer == EOF;
	}
	
	public boolean read() throws IOException {
		
		if (n == 0) {
			fillBuffer();
		}
		
		if (eof()) {
			throw new IOException("EOF");
		}
		
		boolean result = (buffer & 1) == 1;
		buffer >>>= 1;
		n--;
		
		return result;
	}
	
	private void fillBuffer() throws IOException {
		if (n != 0) {
			throw new IllegalStateException();
		}
		buffer = inputStream.read();
		n = 8;
	}
}
